import { loginAPI } from '@/apis/user'
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { useCartStore } from '@/stores/cartStore'
import { mergeCartAPI } from '@/apis/cart'
export const useUserStore = defineStore('user', () => {
  //1.定义管理用户数据的state
  const userInfo = ref({})

  const cartStore = useCartStore()

  //2.定义获取用户数据的action
  const getUserInfo = async ({ account, password }) => {
    const res = await loginAPI({ account, password })
    userInfo.value = res.result
    try {
      await mergeCartAPI(cartStore.cartList.map(item => ({
        skuId: item.skuId,
        selected: item.selected,
        count: item.count
      })))
      await cartStore.getCartList() // 确保使用 await
    } catch (error) {
      console.error('合并购物车失败:', error)
    }
    // console.log('user',userInfo.value);
  }

  const clearUserInfo = () => {
    userInfo.value = {}
    cartStore.clearCart()
  }
  //3.以对象的格式把stste和action return
  return { userInfo, getUserInfo, clearUserInfo }
}, {
  persist: true
})